package upload

import (
	"context"
	"fmt"
	"github.com/bwmarrin/snowflake"
	"github.com/minio/minio-go/v7"
	"net/http"

	"my-zero-tiktok/apps/api/internal/svc"
	"my-zero-tiktok/apps/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadImageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadImageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadImageLogic {
	return &UploadImageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadImageLogic) UploadImage(r *http.Request) (resp *types.UploadImageResponse, err error) {
	// 获取上传的文件
	file, fileHeader, err := r.FormFile("file")
	if err != nil {
		return nil, err
	}
	defer file.Close()
	fmt.Println(fileHeader.Filename, fileHeader.Size)

	src, err := fileHeader.Open()
	if err != nil {
		return nil, err
	}
	defer src.Close()

	ssl := l.svcCtx.Config.OSS.SSL
	client := l.svcCtx.OSSClient
	endpoint := l.svcCtx.Config.OSS.EndPoint
	bucketName := l.svcCtx.Config.OSS.ImageBucketName
	options := minio.PutObjectOptions{ContentType: "image/jpeg"}

	urlStart := "http://"
	if ssl {
		urlStart = "https://"
	}

	// 创建一个新的节点，节点 ID 为 1
	node, err := snowflake.NewNode(1)
	if err != nil {
		return nil, err
	}
	imageName := fmt.Sprintf("%d.jpeg", node.Generate())
	_, err = client.PutObject(context.Background(), bucketName, imageName, src, fileHeader.Size, options)
	imageURL := fmt.Sprintf("%s%s/%s/%s", urlStart, endpoint, bucketName, imageName)
	fmt.Println(imageURL)
	return &types.UploadImageResponse{URL: imageURL}, nil
}
